package com.mew.common.dc.db;

import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.mapper.ErrorCodeMapper;
import com.mew.common.entity.config.ErrorCode;
import com.mew.common.exception.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class MewErrorConfigService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ErrorCodeMapper errorCodeMapper;

    public void loadErrorCode(){
        redisTemplate.delete(RedisConstantValue.CONFIG_ERROR_CODE_LIST);
        Map<Integer, ResponseCode> codeMap = ResponseCode.getCodeMap();
        codeMap.values().forEach(ec -> {
            ErrorCode errorCode = ErrorCode.builder().build().buildData(ec);
            ErrorCode dbEc = errorCodeMapper.selectById(errorCode.getCode());
            if (null == dbEc){
                errorCodeMapper.insert(errorCode);
            }else {
                errorCode.buildData(dbEc);
            }
            redisTemplate.opsForList().leftPush(RedisConstantValue.CONFIG_ERROR_CODE_LIST, errorCode);
        });
    }

    public List<ErrorCode> findErrorCode(){
        List<Object> list = redisTemplate.opsForList().range(RedisConstantValue.CONFIG_ERROR_CODE_LIST, 0, -1);
        return list.stream().map(o -> (ErrorCode)o).collect(Collectors.toList());
    }


}
